// 测试文件上传

const path = require('path');
const fs = require('fs');

const express = require('express');
const multer = require('multer');

// 使用 multer 的 diskStorage 函数来设置 存储路径 和 文件名称
const storage = multer.diskStorage({
    destination: (req, file, callback) => {
        // 使用回调函数第二个参数确定文件存储路径
        callback(null, path.join(__dirname, 'uploads'));
    },
    filename: (req, file, callback) => {
        // 使用回调函数第二个参数确定上传之后的文件名称
        callback(null, file.fieldname + '-' + Date.now() + '-' + file.originalname);
    }
});

const upload = multer({ storage: storage });

const port = 8080;
const app = express();

// 处理静态资源( HTML / CSS / JavaScript / Images )
app.use(express.static('public'));

app.get('/', (req, resp) => {
    resp.redirect('/upload.html');
});

// <input type="file" name="upfile">
app.use('/upload/single', upload.single('upfile'));

app.post('/upload/single', (req, resp, next) => {
    let file = req.file;
    console.log(file);
    resp.send('<h3>回来是回来了，上传成功没有就不知道了</h3>');
});

// <input type="file" name="upfile" multiple>
app.use('/upload/multiple', upload.fields([{ name: 'upfile', maxCount: 5 }]));

// <input type="file" name="upfile" multiple>
app.post('/upload/multiple', (req, resp, next) => {
    // 需要通过 req.files[ fieldName] 来获取相应的文件数组
    let files = req.files['upfile'];
    console.log(files);
    resp.send('<h3>回来是回来了，上传成功没有就不知道了</h3>');
});

app.listen(port, () => {
    console.log(`启动监听(${__filename})`);
});